import { WebPartContext } from "@microsoft/sp-webpart-base";
import { SPHttpClient } from '@microsoft/sp-http';
import moment from 'moment';

// Helper function to convert to Date object
// Handles moment objects, strings, and potentially already Date objects
const toSharePointDate = (dateValue: string | moment.Moment | Date): Date | string => {
  if (dateValue instanceof Date) {
    return dateValue;
  }
  if (moment.isMoment(dateValue)) {
    return dateValue.toDate();
  }
  // If it's a string, try to parse it and convert to Date.
  // This assumes the string is in a format moment can parse.
  const m = moment(dateValue);
  return m.isValid() ? m.toDate() : dateValue; // Return original string if invalid, though ideally should be handled upstream
};

// 定义项目接口
interface IProject {
  Id?: number;
  Title: string;
  Description: string;
  Owner: string;
  Deadline: string | Date;
  Status: string;
  Created: string | Date;
  Modified: string | Date;
}

// 定义任务接口
interface ITask {
  Id?: number;
  Title: string;
  ProjectId: number;
  StartTime: string | Date;
  EndTime: string | Date;
  Priority: string;
  Status: string;
  Category: string;
  Notes: string;
  Created: string | Date;
  Modified: string | Date;
}

// 获取所有项目
export async function fetchProjects(context: WebPartContext): Promise<IProject[]> {
  try {
    const response = await context.spHttpClient.get(
      `${context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('Projects')/items`,
      SPHttpClient.configurations.v1,
      {
        headers: {
          'Accept': 'application/json;odata=nometadata',
          'odata-version': ''
        }
      }
    );

    const responseJson = await response.json();
    console.log('SharePoint Projects API Response:', responseJson.value);
    return responseJson.value.map((item: any): IProject => ({
      Id: item.Id,
      Title: item.Title,
      Description: item.Description || '',
      Owner: item.Owner || '',
      Deadline: item.Deadline,
      Status: item.Status,
      Created: item.Created,
      Modified: item.Modified
    }));
  } catch (error) {
    console.error("Error fetching projects:", error);
    throw error;
  }
}

// 获取所有任务
export async function fetchTasks(context: WebPartContext): Promise<ITask[]> {
  try {
    const response = await context.spHttpClient.get(
      `${context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('Tasks')/items`,
      SPHttpClient.configurations.v1,
      {
        headers: {
          'Accept': 'application/json;odata=nometadata',
          'odata-version': ''
        }
      }
    );

    const responseJson = await response.json();
    return responseJson.value.map((item: any): ITask => ({
      Id: item.Id,
      Title: item.Title,
      ProjectId: item.ProjectId,
      StartTime: item.StartTime,
      EndTime: item.EndTime,
      Priority: item.Priority,
      Status: item.Status,
      Category: item.Category,
      Notes: item.Notes || '',
      Created: item.Created,
      Modified: item.Modified
    }));
  } catch (error) {
    console.error("Error fetching tasks:", error);
    throw error;
  }
}

// 创建新项目
export async function createProject(project: IProject, context: WebPartContext): Promise<IProject> {
  try {
    // Ensure all date values are strings
    const formattedProject = {
      ...project,
      Deadline: toSharePointDate(project.Deadline),
      Created: toSharePointDate(project.Created),
      Modified: toSharePointDate(project.Modified)
    };

    const requestBody = {
      Title: formattedProject.Title,
      Description: formattedProject.Description,
      Owner: formattedProject.Owner,
      Deadline: formattedProject.Deadline,
      Status: formattedProject.Status
    };

    const response = await context.spHttpClient.post(
      `${context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('Projects')/items`,
      SPHttpClient.configurations.v1,
      {
        headers: {
          'Accept': 'application/json;odata=nometadata',
          'Content-type': 'application/json;odata=nometadata',
          'odata-version': ''
        },
        body: JSON.stringify(requestBody)
      }
    );

    const responseJson = await response.json();
    return {
      Id: responseJson.Id,
      Title: responseJson.Title,
      Description: responseJson.Description || '',
      Owner: responseJson.Owner || '',
      Deadline: responseJson.Deadline,
      Status: responseJson.Status,
      Created: responseJson.Created,
      Modified: responseJson.Modified
    };
  } catch (error) {
    console.error("Error creating project:", error);
    throw error;
  }
}

// 创建新任务
export async function createTask(task: ITask, context: WebPartContext): Promise<ITask> {
  try {
    // 打印原始数据
    console.log('Original task data:', task);

    // 确保所有字段都是字符串类型
    const formattedTask = {
      Title: String(task.Title),
      ProjectId: String(task.ProjectId),
      StartTime: toSharePointDate(task.StartTime),
      EndTime: toSharePointDate(task.EndTime),
      Priority: String(task.Priority),
      Status: String(task.Status),
      Category: String(task.Category),
      Notes: String(task.Notes || ''),
      Created: toSharePointDate(task.Created),
      Modified: toSharePointDate(task.Modified)
    };

    // 打印格式化后的数据
    console.log('Formatted task data:', formattedTask);

    const requestBody = {
      Title: formattedTask.Title,
      ProjectId: formattedTask.ProjectId,
      StartTime: formattedTask.StartTime,
      EndTime: formattedTask.EndTime,
      Priority: formattedTask.Priority,
      Status: formattedTask.Status,
      Category: formattedTask.Category,
      Notes: formattedTask.Notes
    };

    // 打印最终发送的数据
    console.log('Request body:', requestBody);

    const response = await context.spHttpClient.post(
      `${context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('Tasks')/items`,
      SPHttpClient.configurations.v1,
      {
        headers: {
          'Accept': 'application/json;odata=nometadata',
          'Content-type': 'application/json;odata=nometadata',
          'odata-version': ''
        },
        body: JSON.stringify(requestBody)
      }
    );

    if (!response.ok) {
      const errorData = await response.json();
      console.error('SharePoint API Error:', errorData);
      throw new Error(`SharePoint API Error: ${JSON.stringify(errorData)}`);
    }

    const responseJson = await response.json();
    console.log('SharePoint Response:', responseJson);

    return {
      Id: responseJson.Id,
      Title: responseJson.Title,
      ProjectId: parseInt(responseJson.ProjectId),
      StartTime: responseJson.StartTime,
      EndTime: responseJson.EndTime,
      Priority: responseJson.Priority,
      Status: responseJson.Status,
      Category: responseJson.Category,
      Notes: responseJson.Notes || '',
      Created: responseJson.Created,
      Modified: responseJson.Modified
    };
  } catch (error) {
    console.error("Error creating task:", error);
    if (error instanceof Error) {
      console.error("Error details:", error.message);
    }
    throw error;
  }
}

// 更新项目
export async function updateProject(project: IProject, context: WebPartContext): Promise<IProject> {
  try {
    const response = await context.spHttpClient.post(
      `${context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('Projects')/items(${project.Id})`,
      SPHttpClient.configurations.v1,
      {
        headers: {
          'Accept': 'application/json;odata=nometadata',
          'Content-type': 'application/json;odata=nometadata',
          'odata-version': '',
          'IF-MATCH': '*',
          'X-HTTP-Method': 'MERGE'
        },
        body: JSON.stringify({
          Title: project.Title,
          Description: project.Description,
          Owner: project.Owner,
          Deadline: toSharePointDate(project.Deadline),
          Status: project.Status,
          Modified: toSharePointDate(moment())
        })
      }
    );

    if (!response.ok) {
      throw new Error(`Failed to update project: ${response.statusText}`);
    }

    // MERGE operation doesn't return a response body, so we return the updated project
    return {
      ...project,
      Modified: toSharePointDate(moment())
    };
  } catch (error) {
    console.error("Error updating project:", error);
    throw error;
  }
}

// 更新任务
export async function updateTask(task: ITask, context: WebPartContext): Promise<ITask> {
  try {
    const response = await context.spHttpClient.post(
      `${context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('Tasks')/items(${task.Id})`,
      SPHttpClient.configurations.v1,
      {
        headers: {
          'Accept': 'application/json;odata=nometadata',
          'Content-type': 'application/json;odata=nometadata',
          'odata-version': '',
          'IF-MATCH': '*',
          'X-HTTP-Method': 'MERGE'
        },
        body: JSON.stringify({
          Title: task.Title,
          ProjectId: task.ProjectId,
          StartTime: toSharePointDate(task.StartTime),
          EndTime: toSharePointDate(task.EndTime),
          Priority: task.Priority,
          Status: task.Status,
          Category: task.Category,
          Notes: task.Notes,
          Modified: toSharePointDate(moment()),
          Created: toSharePointDate(task.Created)
        })
      }
    );

    if (!response.ok) {
      throw new Error(`Failed to update task: ${response.statusText}`);
    }

    // MERGE operation doesn't return a response body, so we return the updated task
    return {
      ...task,
      Modified: toSharePointDate(moment()),
      Created: toSharePointDate(task.Created)
    };
  } catch (error) {
    console.error("Error updating task:", error);
    throw error;
  }
}

// 删除任务
export async function deleteTask(taskId: number, context: WebPartContext): Promise<void> {
  try {
    await context.spHttpClient.post(
      `${context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('Tasks')/items(${taskId})`,
      SPHttpClient.configurations.v1,
      {
        headers: {
          'Accept': 'application/json;odata=nometadata',
          'Content-type': 'application/json;odata=nometadata',
          'odata-version': '',
          'IF-MATCH': '*',
          'X-HTTP-Method': 'DELETE'
        }
      }
    );
  } catch (error) {
    console.error("Error deleting task:", error);
    throw error;
  }
}

// 删除项目及其所有关联任务
export async function deleteProject(projectId: number, context: WebPartContext): Promise<void> {
  try {
    // 删除项目
    await context.spHttpClient.post(
      `${context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('Projects')/items(${projectId})`,
      SPHttpClient.configurations.v1,
      {
        headers: {
          'Accept': 'application/json;odata=nometadata',
          'Content-type': 'application/json;odata=nometadata',
          'odata-version': '',
          'IF-MATCH': '*',
          'X-HTTP-Method': 'DELETE'
        }
      }
    );

    // 获取并删除所有关联任务
    const allTasks = await fetchTasks(context);
    const projectTasks = allTasks.filter(task => Number(task.ProjectId) === Number(projectId));

    const deleteTasksPromises = projectTasks.map(task => deleteTask(task.Id!, context));
    await Promise.all(deleteTasksPromises);

  } catch (error) {
    console.error("Error deleting project and associated tasks:", error);
    throw error;
  }
} 